const dotenv = require('dotenv');
dotenv.config(); // 加载环境变量
const mongoose = require("mongoose");
const _ = require('lodash'); // CommonJS
const { admin, server } = require('../models/Admin');
const { User, UserSwiper, SettledUser, tags, dynamicsTags, dynamics, OrdersSchema } = require('../models/User');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { sendResponse, sendError } = require('../utils/response');
const { error } = require('console');
const { status } = require('express/lib/response');

//管理员登录
exports.login = async (req, res, next) => {
    try {
        const { account, password } = req.body;

        if (!account || !password) {
            throw new Error('登录信息不能为空！');
        }

        const user = await admin.findOne({ account });
        //存在就直接生成token返回token信息,不存在添加进数据库新增用户
        if (user) {
            //用户的密码，数据库用户的密码进行对比
            const passWordNew = await bcrypt.compare(password, user.password);
            if (passWordNew) {
                sendResponse(res, {
                    userid: user._id,
                    account: user.account,
                    token: await jwt.sign({ id: user._id }, process.env.ADMIN_JWT_SECRET, {
                        expiresIn: process.env.ADMIN_JWT_EXPIRES_IN
                    }),
                }, 200, '登录成功！');
            } else {
                throw new Error('密码输入错误！');
            }
        } else {
            //如果用户没有存在在数据库就直接创建一个用户 
            //数值越大越安全但也越慢也就是加密强度
            const salt = await bcrypt.genSalt(10);
            //保存到数据库
            const createUser = await admin.create({
                account,
                password: await bcrypt.hash(password, salt),//密码加密
            });

            if (createUser) {
                sendResponse(res, {
                    userid: createUser.id,
                    account: account,
                    token: await jwt.sign({ id: createUser.id }, process.env.ADMIN_JWT_SECRET, {
                        expiresIn: process.env.ADMIN_JWT_EXPIRES_IN || '24h' // 设置过期时间
                    }),
                }, 200, '注册成功！');
            } else {
                throw new Error('服务器错误！');
            }
        }
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取用户端用户列表
exports.getUsers = async (req, res, next) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        // 1. 参数处理（带默认值）
        const page = Math.max(1, parseInt(req.query.page) || 1); // 最小第1页
        const size = Math.min(100, parseInt(req.query.pageSize) || 10); // 最大100条
        const keyword = req.query.keyword;//用户手机号

        // 1. 安全处理关键词（防止正则注入）
        const sanitize = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const safeKeyword = sanitize(keyword);

        // 2. 构建模糊查询条件
        const query = keyword
            ? {
                account: {
                    $regex: safeKeyword,  // 包含关键字
                    $options: 'i'         // 不区分大小写（可选）
                }
            }
            : {};

        //因为数据库查询返回的是数组，而数组没有clone方法所以延迟执行
        const user = User.find(query);

        // 2. 核心计算
        const skip = (page - 1) * size;
        const [total, data] = await Promise.all([
            User.countDocuments(query),      // 获取总数
            user.clone().skip((page - 1) * size).limit(size).exec() // 显式执行查询
        ]);

        sendResponse(res, {
            page,
            size,
            total,
            totalPages: Math.ceil(total / size),
            data: data ? data : []
        }, 200, '操作成功！');

    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//轮播图上传
exports.uploadSwiper = async (req, res, next) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const { swipers, link } = req.body;

        if (!swipers) {
            throw new Error('参数不能为空！');
        }

        const user = await UserSwiper.create({
            imgUrl: swipers,
            link: link
        });

        if (!user) {
            throw new Error('创建失败！');
        }

        if (UserSwiper.countDocuments().length >= 6) {
            throw new Error('轮播图最多只能存储6张！');
        }

        sendResponse(res, null, 200, '上传成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//通过id删除指定轮播图
exports.swiperDelect = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        //验证id格式
        if (!mongoose.Types.ObjectId.isValid(id)) {
            return res.status(400).json({ error: "无效的 ID 格式" });
        }

        // 查找并删除
        const deletedBook = await UserSwiper.findByIdAndDelete(id);

        if (!deletedBook) {
            throw new Error('id对应数据不存在！');
        }

        sendResponse(res, null, 200, '删除成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//通过用户id删除搭子审核记录
exports.userSchemaDelect = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        //验证id格式
        if (!mongoose.Types.ObjectId.isValid(id)) {
            return res.status(400).json({ error: "无效的 ID 格式" });
        }

        // 查找并删除
        const settledUser = await SettledUser.findOne({ userid: id });

        if (!settledUser) {
            return sendResponse(res, null, 404, 'ID 对应的入驻用户数据不存在');
        }

        const userId = settledUser.userid;

        await SettledUser.deleteOne({ _id: settledUser._id });

        const updatedUser = await User.findOneAndUpdate(
            { _id: userId },
            { $set: { userType: 0 } },
            {
                new: true,
                // 防止意外修改用户名
                projection: { username: 0 }
            }
        );

        if (!updatedUser) {
            throw new Error('用户更新失败');
        }

        sendResponse(res, null, 200, '删除并更新成功！');

    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取管理端用户列表详情
exports.getUsersDetails = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        if (!id) {
            throw new Error('id不能为空！');
        }

        const user = await User.findOne({ _id: req.query.id });

        if (!user) {
            throw new Error('查无此用户！');
        }

        sendResponse(res, user, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取全部状态搭子列表
exports.getSettledUsers = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        // 1. 参数处理（带默认值）
        const page = Math.max(1, parseInt(req.query.page) || 1); // 最小第1页
        const size = Math.min(100, parseInt(req.query.pageSize) || 10); // 最大100条
        const keyword = req.query.keyword;//用户手机号

        // 1. 安全处理关键词（防止正则注入）
        const sanitize = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const safeKeyword = sanitize(keyword);

        // 2. 构建模糊查询条件
        const query = keyword
            ? {
                realName: {
                    $regex: safeKeyword,  // 包含关键字
                    $options: 'i'         // 不区分大小写（可选）
                }
            }
            : {};

        //因为数据库查询返回的是数组，而数组没有clone方法所以延迟执行
        const user = SettledUser.find(query);

        // 2. 核心计算
        const skip = (page - 1) * size;
        const [total, data] = await Promise.all([
            SettledUser.countDocuments(query),
            SettledUser.find(query)
                .skip((page - 1) * size)
                .limit(size)
                .exec()
        ]);

        sendResponse(res, {
            page,
            size,
            total,
            totalPages: Math.ceil(total / size),
            data: data ? data : []
        }, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取全部状态动态列表
exports.getDynamicsLists = async (req, res) => {
    try {
        // 1. 参数处理（带安全校验）
        const page = Math.max(1, parseInt(req.query.page) || 1);
        const size = Math.min(100, parseInt(req.query.pageSize) || 10);
        const query = req.query.status ? { 'partnerAudit.status': req.query.status } : {};

        // 2. 并行查询
        const [total, rawData] = await Promise.all([
            dynamics.countDocuments(query),
            dynamics.find(query)
                .populate({
                    path: 'userid',
                    select: 'username avatar', // 精确控制字段
                    options: { lean: true }    // 提升性能
                })
                .skip((page - 1) * size)
                .limit(size)
                .lean()
        ]);

        // 3. 数据重组（安全处理未关联的情况）
        const processedData = rawData.map(item => ({
            ..._.omit(item, ['__v', 'userid']), // 过滤多余字段
            userinfo: {
                id: item.userid?._id?.toString() || 'unknown',
                username: item.userid?.username || '佚名用户',
                avatar: item.userid?.avatar || '/default.jpg'
            }
        }));

        // 4. 返回结果
        sendResponse(res, {
            page,
            size,
            total,
            totalPages: Math.ceil(total / size),
            data: processedData
        }, 200);
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//搭子审核
exports.SettledUsersReview = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const { id, userid, status, reviewNote } = req.body;

        const user = await User.findOne({ _id: userid });

        if (!user) {
            throw new Error('用户不存在，数据错误！');
        }

        const SettledData = await SettledUser.findOne({ _id: id });

        if (!SettledData) {
            throw new Error('id对应的键值不存在！');
        }

        if (status == 'rejected') {
            if (!reviewNote) {
                throw new Error('请填写审核拒绝的理由！');
            }
        }

        const UpdateSettledUser = await SettledUser.updateOne({ _id: SettledData._id }, {
            'partnerAudit.status': status,
            'partnerAudit.reviewer': user._id,
            'partnerAudit.reviewNote': reviewNote,
            'partnerAudit.reviewedAt': Date.now()
        });

        const UpdateUser = await User.updateOne({ _id: user._id }, {
            'userType': 1,
            'username': SettledData.realName || '',
            'avatar': SettledData.avatar || '',
        });

        if (!UpdateSettledUser && !UpdateUser) {
            throw new Error('数据更新审核失败！');
        }

        sendResponse(res, null, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//动态审核
exports.dynamicsReview = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const { id, userid, status, reviewNote } = req.body;

        const user = await User.findOne({ _id: userid });

        if (!user) {
            throw new Error('用户不存在，数据错误！');
        }

        const SettledData = await dynamics.findOne({ _id: id });

        if (!SettledData) {
            throw new Error('id对应的键值不存在！');
        }

        if (status == 'rejected') {
            if (!reviewNote) {
                throw new Error('请填写审核拒绝的理由！');
            }
        }

        const UpdateDynamics = await dynamics.updateOne({ _id: SettledData._id }, {
            'partnerAudit.status': status,
            'partnerAudit.reviewNote': reviewNote
        });

        if (!UpdateDynamics) {
            throw new Error('数据更新审核失败！');
        }

        sendResponse(res, null, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//通过id获取搭子详情
exports.getSettledUserDetails = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        if (!id) {
            throw new Error('id不能为空！');
        }

        const user = await SettledUser.findOne({ _id: req.query.id });

        if (!user) {
            throw new Error('查无此用户！');
        }

        sendResponse(res, user, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//通过id获取动态详情
exports.getDynamicsDetails = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        if (!id) {
            throw new Error('id不能为空！');
        }

        const user = await dynamics.findOne({ _id: req.query.id });

        if (!user) {
            throw new Error('当前id查询结果为空！');
        }

        sendResponse(res, user, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//配置客服企业微信二维码和电话
exports.service = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const { qrcode_link1, qrcode_link2, server_phone1, server_phone2, server_id } = req.body;

        const total = await server.countDocuments(server_id ? { _id: server_id } : {});

        if (total === 0) {
            var createServer = await server.create({
                'partnerServer.qrcode1': qrcode_link1,
                'partnerServer.qrcode2': qrcode_link2,
                'partnerServer.phone1': server_phone1,
                'partnerServer.phone2': server_phone2,
            });

            if (!createServer) {
                throw new Error('创建客服配置失败！');
            }

            sendResponse(res, null, 200, '保存成功！');
        } else {
            var updateServer = await server.updateOne({ _id: server_id }, {
                'partnerServer.qrcode1': qrcode_link1,
                'partnerServerqrcode2': qrcode_link2,
                'partnerServer.phone1': server_phone1,
                'partnerServer.phone2': server_phone2,
            });

            if (!updateServer) {
                throw new Error('编辑客服配置失败！');
            }

            sendResponse(res, null, 200, '编辑成功！');
        }

    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取系统配置项全部一起返回
exports.getSystemConfig = async (req, res) => {
    try {
        const { type } = req.query;

        if (!type) {
            throw new Error('查询类型不能为空！');
        }

        switch (type) {
            case 'server':
                const servers = await server.find();

                if (!servers) {
                    throw new Error('查询结果为空！');
                }

                sendResponse(res, servers, 200, '操作成功！');
                break;
            default:
                throw new Error('查询参数不符合查询条件！');
        }

    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//tag标签新增
exports.Newtag = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const { tag, url } = req.body;
        if (!tag) {
            throw new error('参数不能为空！');
        }

        const tagText = await tags.create({
            tag,
            url
        });

        if (!tagText) {
            throw new error('数据创建失败！');
        }

        sendResponse(res, null, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取tag标签列表
exports.gettags = async (req, res) => {
    try {
        // 1. 参数处理（带默认值）
        const page = Math.max(1, parseInt(req.query.page) || 1); // 最小第1页
        const size = Math.min(100, parseInt(req.query.pageSize) || 10); // 最大100条

        //因为数据库查询返回的是数组，而数组没有clone方法所以延迟执行
        const user = tags.find();

        // 2. 核心计算
        const skip = (page - 1) * size;
        const [total, data] = await Promise.all([
            tags.countDocuments(),      // 获取总数
            user.clone().skip((page - 1) * size).limit(size).exec() // 显式执行查询
        ]);

        sendResponse(res, {
            page,
            size,
            total,
            totalPages: Math.ceil(total / size),
            data: data ? data : []
        }, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//删除tag标签
exports.deltags = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        //验证id格式
        if (!mongoose.Types.ObjectId.isValid(id)) {
            return res.status(400).json({ error: "无效的 ID 格式" });
        }

        // 查找并删除
        const deletedBook = await tags.findByIdAndDelete(id);

        if (!deletedBook) {
            throw new Error('id对应数据不存在！');
        }

        sendResponse(res, null, 200, '删除成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//tag话题标签新增
exports.NewdynamicsTags = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const { tag, url } = req.body;
        if (!tag) {
            throw new error('参数不能为空！');
        }

        const tagText = await dynamicsTags.create({
            tag,
            url
        });

        if (!tagText) {
            throw new error('数据创建失败！');
        }

        sendResponse(res, null, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取tag话题标签列表
exports.getdynamicsTags = async (req, res) => {
    try {
        // 1. 参数处理（带默认值）
        const page = Math.max(1, parseInt(req.query.page) || 1); // 最小第1页
        const size = Math.min(100, parseInt(req.query.pageSize) || 10); // 最大100条

        //因为数据库查询返回的是数组，而数组没有clone方法所以延迟执行
        const user = dynamicsTags.find();

        // 2. 核心计算
        const skip = (page - 1) * size;
        const [total, data] = await Promise.all([
            dynamicsTags.countDocuments(),      // 获取总数
            user.clone().skip((page - 1) * size).limit(size).exec() // 显式执行查询
        ]);

        sendResponse(res, {
            page,
            size,
            total,
            totalPages: Math.ceil(total / size),
            data: data ? data : []
        }, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//删除tag话题标签
exports.dynamicsTagsdel = async (req, res) => {
    try {
        getTokenCheck(req, res);

        const token = await jwt.verify(req.headers.authorization.split(' ')[1], process.env.ADMIN_JWT_SECRET);

        const getUserId = await admin.findOne({ _id: token.id })

        if (!getUserId) {
            throw new Error('用户不存在！');
        }

        const id = req.query.id;

        //验证id格式
        if (!mongoose.Types.ObjectId.isValid(id)) {
            throw new Error('无效的 ID 格式!');
        }

        // 查找并删除
        const deletedBook = await dynamicsTags.findByIdAndDelete(id);

        if (!deletedBook) {
            throw new Error('id对应数据不存在！');
        }

        sendResponse(res, null, 200, '删除成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//获取用户端全部订单
exports.getOrderLists = async (req, res) => {
    try {
        // 1. 参数处理（带默认值）
        const page = Math.max(1, parseInt(req.query.page) || 1); // 最小第1页
        const size = Math.min(100, parseInt(req.query.pageSize) || 10); // 最大100条

        //因为数据库查询返回的是数组，而数组没有clone方法所以延迟执行
        const orders = OrdersSchema.find();

        // 2. 核心计算
        const skip = (page - 1) * size;
        const [total, data] = await Promise.all([
            OrdersSchema.countDocuments(),      // 获取总数
            orders.clone().skip((page - 1) * size).limit(size).exec() // 显式执行查询
        ]);

        sendResponse(res, {
            page,
            size,
            total,
            totalPages: Math.ceil(total / size),
            data: data ? data : []
        }, 200, '操作成功！');
    } catch (error) {
        sendError(res, error.message, 400);
    }
}

//token校验
const getTokenCheck = async (req, res) => {
    try {
        const headerstoken = req.headers.authorization;
        if (headerstoken.split(' ').lenght <= 1) {
            throw new Error('请求头无token！');
        }

        const token = await jwt.verify(headerstoken.split(' ')[1], process.env.ADMIN_JWT_SECRET);
        if (!token) {
            throw new Error('无效token！');
        }
    } catch (error) {
        sendError(res, error.message, 430);
    }
}